package com.cap.bts.crmdp.dealer.logistic.controller;

import java.io.IOException;

/******************************************************************************
 * @File name   :      MaintainMemberController.java
 *
 * @Author      :      ANMA
 *
 * @Date        :      Jul 20, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * ----------------------------------------------------------------------------
 * Date                         Who         Version         Comments
 * Jul 20, 2015 7:03:02 PM    ANMA      1.0            Initial Version
 *****************************************************************************/

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.cap.bts.commonfunc.common.service.IUniqueCodeGenerateService;
import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.crmdp.dealer.logistic.constants.FileType;
import com.cap.bts.crmdp.dealer.logistic.constants.LogisticConstants;
import com.cap.bts.crmdp.dealer.logistic.dao.IMaintainLogisticDao;
import com.cap.bts.crmdp.dealer.logistic.dto.LogisticDataDto;
import com.cap.bts.crmdp.dealer.logistic.dto.LogisticImportDto;
import com.cap.bts.crmdp.dealer.logistic.dto.LogisticQueryDto;
import com.cap.bts.crmdp.dealer.logistic.dto.LogisticRelatedDto;
import com.cap.bts.crmdp.dealer.logistic.dto.LogisticResultsDto;
import com.cap.bts.crmdp.dealer.logistic.dto.LogisticTemplateDto;
import com.cap.bts.crmdp.dealer.logistic.service.IMaintainLogisticService;
import com.cap.bts.crmdp.dealer.masterdata.dao.IMaintainDealerDao;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.usermgnt.domain.User;

/**
 * 
 */
@Controller
@RequestMapping(value = "/crmdp/dealer/logistic")
public class MaintainLogisticController extends BaseController implements ServletContextAware{
    private static final Logger LOGGER = Logger.getLogger(MaintainLogisticController.class);

    @Autowired
    private ServletContext sc;

    @Autowired
    private MessageSource messageSource;
    @Resource(name = "uniqueCodeGenerateqService")
    private IUniqueCodeGenerateService uniqueCodeGenerateService;
    @Autowired
    IMaintainDealerDao  maintainDealerDao;
    
	static final String GETMAINTAINLOGISTICPAGE = "getMaintainLogisticPage";
    static final String GETRECEIVELOGISTICPAGE = "getReceiveLogisticPage";
    static final String TRANSACTIONSTARTDATE="transactionStartDate";
    static final String TRANSACTIONENDDATE="transactionEndDate";
    static final String DEALERINFO="dealerInfo";
    static final String ORDERNUM="orderNum";
    static final String ORDERSTATUS="orderStatus";
    static final String EXPRESSCOM="expressCom";
    static final String EXPRESSNUM="expressNum";
    static final String CARDNAME="cardName";
    static final String SMSNAME="smsName";
    static final String DEALERNO="dealerNo";
    static final String USERID="userId";
    static final String ORDERNO="orderNo";
    static final String RESULTLIST="resultList";
    static final String MAINTAINLOGISTIC="/logistic/maintainLogistic";
    static final String PRINTLOGISTIC="/logistic/printLogistic";
    static final String CREATELOGISTIC="/logistic/createLogistic";
    static final String UPLOADLOGISTIC="/logistic/uploadLogistic";
    static final String EDITLOGISTIC="/logistic/editLogistic";
    
	@Autowired
	IMaintainLogisticService maintainLogisticService;
	@Resource(name = "maintainLogisticDao")
    private IMaintainLogisticDao maintainLogisticDao;
	
	/**
	 * 查询配送信息
	 */
	@RequestMapping(value = "/toQueryLogisitcPage")
	public String toQueryLogisticPage(LogisticQueryDto dto, 
	    Model model, HttpServletRequest request) throws AppException {
        User queryUser = UserUtil.getCurrentUser();
        if(queryUser!=null){
            dto.setUserId(queryUser.getId().toString());
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	    LogisticResultsDto result = new LogisticResultsDto();
        if(dto != null) {
            if(Utils.isNullOrEmpty(dto.getTransactionStartDate())
                ||Utils.isNullOrEmpty(dto.getTransactionEndDate())){
                dto.setTransactionStartDate(df.format(new Date()));
                dto.setTransactionEndDate(df.format(new Date()));
            }
            dto.setPaging(true);
            result = maintainLogisticService.queryLogisticData(dto);
            model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
            request.getSession().setAttribute(TRANSACTIONSTARTDATE, dto.getTransactionStartDate());
            request.getSession().setAttribute(TRANSACTIONENDDATE, dto.getTransactionEndDate());
            request.getSession().setAttribute(DEALERINFO, dto.getDealerInfo());
            request.getSession().setAttribute(ORDERNUM, dto.getOrderNum());
            request.getSession().setAttribute(ORDERSTATUS, dto.getOrderStatus());
            request.getSession().setAttribute(EXPRESSCOM, dto.getExpressCom());
            request.getSession().setAttribute(EXPRESSNUM, dto.getExpressNum());
            request.getSession().setAttribute(USERID, dto.getUserId());
        }
        request.getSession().setAttribute(GETMAINTAINLOGISTICPAGE, dto);
        model.addAttribute(RESULTLIST, result.getResultList());
        model.addAttribute("dto", dto);
        return MAINTAINLOGISTIC;
	}

    /**
     * 打印配送信息
     */
    @RequestMapping(value = "/toPrintLogisticPage")
    public String toPrintLogisticPage(LogisticQueryDto dtoForPrint, 
        Model model, HttpServletRequest requestForPrint) throws AppException {
        User queryUser = UserUtil.getCurrentUser();
        if(queryUser!=null){
            dtoForPrint.setUserId(queryUser.getId().toString());
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        LogisticResultsDto result = new LogisticResultsDto();
        if(dtoForPrint != null) {
            if(Utils.isNullOrEmpty(dtoForPrint.getTransactionStartDate())
                ||Utils.isNullOrEmpty(dtoForPrint.getTransactionEndDate())){
                dtoForPrint.setTransactionStartDate(df.format(new Date()));
                dtoForPrint.setTransactionEndDate(df.format(new Date()));
            }
            result = maintainLogisticService.queryLogisticDataForPrint(dtoForPrint);
            requestForPrint.getSession().setAttribute(TRANSACTIONSTARTDATE, dtoForPrint.getTransactionStartDate());
            requestForPrint.getSession().setAttribute(TRANSACTIONENDDATE, dtoForPrint.getTransactionEndDate());
            requestForPrint.getSession().setAttribute(DEALERINFO, dtoForPrint.getDealerInfo());
            requestForPrint.getSession().setAttribute(ORDERNUM, dtoForPrint.getOrderNum());
            requestForPrint.getSession().setAttribute(ORDERSTATUS, dtoForPrint.getOrderStatus());
            requestForPrint.getSession().setAttribute(EXPRESSCOM, dtoForPrint.getExpressCom());
            requestForPrint.getSession().setAttribute(EXPRESSNUM, dtoForPrint.getExpressNum());
            requestForPrint.getSession().setAttribute(USERID, dtoForPrint.getUserId());
        }
        requestForPrint.getSession().setAttribute(GETMAINTAINLOGISTICPAGE, dtoForPrint);
        model.addAttribute(RESULTLIST, result.getResultForPrintList());
        model.addAttribute("dto", dtoForPrint);
        return PRINTLOGISTIC;
    }
	/**
     * 转向添加配送信息界面
     */
    @RequestMapping(value = "/toCreateLogisitcPage")
    public String toCreateLogisticPage(Model model, HttpServletRequest request) throws AppException {
        LogisticDataDto dto = new LogisticDataDto();
        List<LogisticRelatedDto> cardName = maintainLogisticDao.getCardName();
        model.addAttribute(CARDNAME, cardName);
        List<LogisticRelatedDto> smsName = maintainLogisticDao.getSMSName();
        model.addAttribute(SMSNAME, smsName);
        request.getSession().setAttribute(DEALERNO,null);
        request.getSession().setAttribute(ORDERNO,null);
        model.addAttribute("dto", dto);
        return CREATELOGISTIC;
    }
    /**
     * 转向上传界面
     */
    @RequestMapping(value = "/toUploadLogisitcPage")
    public String toUploadLogisticPage(Model model, HttpServletRequest request) throws AppException {
        LogisticDataDto dto = new LogisticDataDto();
        model.addAttribute("dto", dto);
        model.addAttribute("uploadResult", false); 
        model.addAttribute("suc", true);
        return UPLOADLOGISTIC;
    }
    /**
     * 下载模板
     */
    @RequestMapping(value = "/toDownloadLogisitcPage")
     public ModelAndView toDownloadLogisitcPage(Model model,HttpServletRequest request) throws AppException {
     
     ModelAndView modelAndView = new ModelAndView();
     LogisticTemplateDto templateDto = new LogisticTemplateDto();
     List<LogisticRelatedDto> cardNames = maintainLogisticDao.getCardName();
     if (cardNames != null) {
         Map<String, String> map = new HashMap<String, String>();
         for (LogisticRelatedDto data : cardNames) {
             map.put(String.valueOf(data.getId()), data.getCardName());
         }
         templateDto.setMapCardName(map);
     }
     Map<String, String> mapDealer = maintainLogisticDao.getDealers();
     if(mapDealer != null){
         templateDto.setMapDealerNo(mapDealer);
     }
     
     modelAndView.addObject("LogisticTemplate.xlsx",templateDto);
     modelAndView.setViewName("exportLogisticTemplate");
     return modelAndView;
 }
    
    /**
     * 处理上传数据
     */
    @RequestMapping(value = "/uploadLogisitcPage")
    public String uploadLogisticPage(@ModelAttribute("dto")LogisticImportDto logisticImportDto,
              Model model) {
        LogisticResultsDto result = new LogisticResultsDto();   
        User createUser = UserUtil.getCurrentUser();
        try {
          MultipartFile file = logisticImportDto.getLogisticFile();           
          if(file==null  || file.getSize()<=0){
              logisticImportDto.setErrorMsg(messageSource.getMessage("excel.file.notEmpty",null, Locale.CHINA));
          }else if(!file.getOriginalFilename().endsWith(FileType.XLS.getValue())&& 
                  !file.getOriginalFilename().endsWith(FileType.XLSX.getValue())){
              logisticImportDto.setErrorMsg(messageSource.getMessage("excel.file.type", null, Locale.CHINA));
          }else{ 
              if(createUser!=null){
                  result = maintainLogisticService.handleImportInBackground(file.getOriginalFilename(), 
                      file.getInputStream() ,"Logistic_template_items.xml", "logisticTemplateItems", "Sheet1",createUser.getId().toString());
              }                 
              model.addAttribute("fileName", file.getOriginalFilename());
              
              if(result.getImportList() != null && !result.getImportList().isEmpty()){
                    model.addAttribute("uploadResult", true); 
                    model.addAttribute("suc", false);
                } else {
                    model.addAttribute("uploadResult", true);
                    model.addAttribute("suc", true);
                }
              
          }
        } catch (Exception e) {   
            model.addAttribute("uploadResult", false);
            model.addAttribute("suc", false);
            LOGGER.error(e);
        }               
        model.addAttribute("logisticImportDto", result.getImportList());
        return UPLOADLOGISTIC;
    }
    /**
     * 判断门店编号
     */
    @RequestMapping(value = "/toCheckDealer")
    @ResponseBody
    public boolean toCheckDealer(String dealerNo) throws AppException {
        if(!Utils.isNullOrEmpty(dealerNo)){
            String dealerId = maintainLogisticDao.getDealerId(dealerNo);
            if(!Utils.isNullOrEmpty(dealerId)){
                return false;
            }
        }
        return true;
    }
    /**
     * 添加配送信息
     */
    @RequestMapping(value = "/toAddLogisitcPage")
    public String toAddLogisticPage(LogisticDataDto dto,Model model,
        HttpServletRequest request) throws AppException {
        User createUser = UserUtil.getCurrentUser();
        if(createUser!=null){
            dto.setUserId(createUser.getId().toString());
        }
        try {
            if(dto!=null){
                dto.setDealerNo(java.net.URLDecoder.decode(dto.getDealerNo(),
                LogisticConstants.ENCODE_UTF_8));
                dto.setCardName(java.net.URLDecoder.decode(dto.getCardList(),
                LogisticConstants.ENCODE_UTF_8));
                dto.setExpressCom(java.net.URLDecoder.decode(dto.getExpressCom(),
                LogisticConstants.ENCODE_UTF_8));
                dto.setExpressNo(java.net.URLDecoder.decode(dto.getExpressNo(),
                LogisticConstants.ENCODE_UTF_8));
            }
        } catch (UnsupportedEncodingException e) {
            throw new AppException("toAddLogisitcPage", e);
        }
        if(dto!=null){
            dto.setOrderNo(dto.getOrderNo());
            dto.setShipDate(dto.getShipDate());
            dto.setEstimatedArriveDate(dto.getEstimatedArriveDate());
            //代替orderNo or not
            dto.setTransactionNo(uniqueCodeGenerateService.generateLogitsticNo());
        }
        List<LogisticRelatedDto> cardName = maintainLogisticDao.getCardName();        
        model.addAttribute(CARDNAME, cardName);
        List<LogisticRelatedDto> smsName = maintainLogisticDao.getSMSName();
        model.addAttribute(SMSNAME, smsName);
        if((dto != null) && (!maintainLogisticService.insertLogisticInfo(dto))){
            model.addAttribute("flag", "dealerNoWrong");
            model.addAttribute("dto", dto);
            return CREATELOGISTIC;
        }
        LogisticDataDto newDto = new LogisticDataDto();
        model.addAttribute("flag", "addSuccess");
        model.addAttribute("dto", newDto);
        return CREATELOGISTIC;
    }
    /**
     * 转向修改配送信息
     */
    @RequestMapping(value = "/toEditLogisitcPage/{id}", method = RequestMethod.GET)
    public String toEditLogisticPage(@PathVariable("id") String id, Model model,
        HttpServletRequest request) throws AppException {
        LogisticDataDto dto=maintainLogisticService.queryLogisticDataById(id);
        model.addAttribute("dto", dto);
        return EDITLOGISTIC;
    }
    /**
     * 修改配送信息
     * @throws ParseException 
     */
    @RequestMapping(value = "/toUpdateLogisitcPage")
    public String toUpdateLogisticPage(LogisticDataDto dto,
        Model model,HttpServletRequest request) throws AppException {
        User editUser = UserUtil.getCurrentUser();
        if(editUser!=null){
            dto.setUserId(editUser.getId().toString());
        }
        Date date = new Date();
        Date d;
        try {
            d = new SimpleDateFormat(CommonConstants.DATE_FORMAT_YYMMDD).parse(dto.getShipDate().toString());
        } catch (ParseException e) {
            throw new AppException("toUpdateLogisticPage", e);
        }
        if(d.after(date)){
            model.addAttribute("flag", "tooLate");
            LogisticDataDto oldDto=maintainLogisticService.queryLogisticDataById(dto.getId().toString());
            model.addAttribute("dto", oldDto);
            return EDITLOGISTIC;
        }
        if(!maintainLogisticService.editLogisticInfo(dto)){
            model.addAttribute("flag", "canNotUpdate");
            LogisticDataDto oldDto=maintainLogisticService.queryLogisticDataById(dto.getId().toString());
            model.addAttribute("dto", oldDto);
            return EDITLOGISTIC;
        }
        return toQueryLogisitcInfo(new LogisticQueryDto(), model,request);
    }
    /**
     * 删除配送信息
     */
    @RequestMapping(value = "/toDeleteLogisitcPage/{id}", method = RequestMethod.GET)
    public String toDeleteLogisticPage(@PathVariable("id") String id, Model model,
            HttpServletRequest request) throws AppException {
        LogisticQueryDto dto = new LogisticQueryDto();
        if(!maintainLogisticService.deleteLogisticInfo(id)){
            model.addAttribute("flag", "canNotDelete");
        }
        model.addAttribute("dto", dto);
        return toQueryLogisitcInfo(new LogisticQueryDto(), model,request);
    }
    
    @RequestMapping(value = "/queryLogisitcPage")
    public String toQueryLogisitcInfo(LogisticQueryDto dto, Model model,
            HttpServletRequest request) throws AppException {
        LogisticResultsDto result = new LogisticResultsDto();
        if(request.getSession().getAttribute(TRANSACTIONSTARTDATE) != null){
            dto.setTransactionStartDate(request.getSession().getAttribute(TRANSACTIONSTARTDATE).toString());
            }
        if(request.getSession().getAttribute(TRANSACTIONENDDATE) != null){
            dto.setTransactionEndDate(request.getSession().getAttribute(TRANSACTIONENDDATE).toString());
            }
        if(request.getSession().getAttribute(DEALERINFO) != null){
            dto.setDealerInfo(request.getSession().getAttribute(DEALERINFO).toString());
            }
        if(request.getSession().getAttribute(ORDERNUM) != null){
            dto.setOrderNum(request.getSession().getAttribute(ORDERNUM).toString());
            }
        if(request.getSession().getAttribute(ORDERSTATUS) != null){
            dto.setOrderStatus(request.getSession().getAttribute(ORDERSTATUS).toString());
            }
        if(request.getSession().getAttribute(EXPRESSCOM) != null){
            dto.setExpressCom(request.getSession().getAttribute(EXPRESSCOM).toString());
            }
        if(request.getSession().getAttribute(EXPRESSNUM) != null){
            dto.setExpressNum(request.getSession().getAttribute(EXPRESSNUM).toString());
            }
        if(request.getSession().getAttribute(USERID) != null){
            dto.setUserId(request.getSession().getAttribute(USERID).toString());
            }
        if(dto != null){
            dto.setPaging(true);
            result = maintainLogisticService.queryLogisticData(dto);
        }
        if(dto != null) {
             model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        }
        model.addAttribute(RESULTLIST, result.getResultList());
        model.addAttribute("dto", dto);
        return MAINTAINLOGISTIC;
    }

    @RequestMapping(value = "/backToLogisitcPage")
    public String backToQueryLogisitcInfo(Model model,
            HttpServletRequest request) throws AppException {
        LogisticQueryDto backToDto = new  LogisticQueryDto();
        LogisticResultsDto backToResult = new LogisticResultsDto();
        if(request.getSession().getAttribute(TRANSACTIONSTARTDATE) != null){
            backToDto.setTransactionStartDate(request.getSession().getAttribute(TRANSACTIONSTARTDATE).toString());
            }
        if(request.getSession().getAttribute(TRANSACTIONENDDATE) != null){
            backToDto.setTransactionEndDate(request.getSession().getAttribute(TRANSACTIONENDDATE).toString());
            }
        if(request.getSession().getAttribute(DEALERINFO) != null){
            backToDto.setDealerInfo(request.getSession().getAttribute(DEALERINFO).toString());
            }
        if(request.getSession().getAttribute(ORDERNUM) != null){
            backToDto.setOrderNum(request.getSession().getAttribute(ORDERNUM).toString());
            }
        if(request.getSession().getAttribute(ORDERSTATUS) != null){
            backToDto.setOrderStatus(request.getSession().getAttribute(ORDERSTATUS).toString());
            }
        if(request.getSession().getAttribute(EXPRESSCOM) != null){
            backToDto.setExpressCom(request.getSession().getAttribute(EXPRESSCOM).toString());
            }
        if(request.getSession().getAttribute(EXPRESSNUM) != null){
            backToDto.setExpressNum(request.getSession().getAttribute(EXPRESSNUM).toString());
            }
        if(request.getSession().getAttribute(USERID) != null){
            backToDto.setUserId(request.getSession().getAttribute(USERID).toString());
            }
        if(backToDto != null){
            backToDto.setPaging(true);
            backToResult = maintainLogisticService.queryLogisticData(backToDto);
            model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, backToDto.getPager());
        }
        model.addAttribute(RESULTLIST, backToResult.getResultList());
        model.addAttribute("dto", backToDto);
        return MAINTAINLOGISTIC;
    }
    /**
     * 查询接收界面的配送信息
     */
    @RequestMapping(value = "/toQueryLogisitcReceivePage")
    public String toQueryLogisitcReceivePage(LogisticQueryDto receiveDto, 
        Model model, HttpServletRequest request) throws AppException {
        User queryReceiveUser = UserUtil.getCurrentUser();
        if(queryReceiveUser!=null){
            receiveDto.setUserId(Long.toString(queryReceiveUser.getDealerId()));
            //临时修正
            //MasterDataDealerInfo dealerDto=maintainDealerDao.findById(queryReceiveUser.getDealerId())
            receiveDto.setDealerInfo(String.valueOf(queryReceiveUser.getDealerId()));
        }else{
        	String dealerId = request.getParameter("dealerId");
        	if(StringUtils.isNotBlank(dealerId)){
        		
        		receiveDto.setUserId(dealerId);
        		receiveDto.setDealerInfo(dealerId);
        	}
        	
        }
        LogisticResultsDto result = new LogisticResultsDto();
        if(receiveDto != null) {
            receiveDto.setPaging(true);
            result = maintainLogisticService.queryReceiveLogisticData(receiveDto);
            model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, receiveDto.getPager());
            request.getSession().setAttribute(TRANSACTIONSTARTDATE, receiveDto.getTransactionStartDate());
            request.getSession().setAttribute(TRANSACTIONENDDATE, receiveDto.getTransactionEndDate());
            request.getSession().setAttribute(ORDERNUM, receiveDto.getOrderNum());
            request.getSession().setAttribute(ORDERSTATUS, receiveDto.getOrderStatus());
            request.getSession().setAttribute(EXPRESSCOM, receiveDto.getExpressCom());
            request.getSession().setAttribute(EXPRESSNUM, receiveDto.getExpressNum());
            request.getSession().setAttribute(USERID, receiveDto.getUserId());
        }
        request.getSession().setAttribute(GETRECEIVELOGISTICPAGE, receiveDto);
        model.addAttribute(RESULTLIST, result.getResultList());
        model.addAttribute("dto", receiveDto);
        return "/logistic/receivedLogistic";
    }
    /**
     * 查询接收界面的配送信息
     */
    @RequestMapping(value = "/toQueryLogisitcReceivePageForMars")
    public String toQueryLogisitcReceivePageForMars(LogisticQueryDto receiveDto, 
        Model model, HttpServletRequest request, String dealerId) throws AppException {
        if(StringUtils.isNotBlank(dealerId)){
            receiveDto.setUserId(dealerId);
            receiveDto.setDealerInfo(dealerId);
        }else{
        	dealerId = request.getParameter("dealerId");
        	if(StringUtils.isNotBlank(dealerId)){
        		
        		receiveDto.setUserId(dealerId);
        		receiveDto.setDealerInfo(dealerId);
        	}
        	
        }
        LogisticResultsDto result = new LogisticResultsDto();
        if(receiveDto != null) {
            receiveDto.setPaging(true);
            result = maintainLogisticService.queryReceiveLogisticData(receiveDto);
            model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, receiveDto.getPager());
            request.getSession().setAttribute(TRANSACTIONSTARTDATE, receiveDto.getTransactionStartDate());
            request.getSession().setAttribute(TRANSACTIONENDDATE, receiveDto.getTransactionEndDate());
            request.getSession().setAttribute(ORDERNUM, receiveDto.getOrderNum());
            request.getSession().setAttribute(ORDERSTATUS, receiveDto.getOrderStatus());
            request.getSession().setAttribute(EXPRESSCOM, receiveDto.getExpressCom());
            request.getSession().setAttribute(EXPRESSNUM, receiveDto.getExpressNum());
            request.getSession().setAttribute(USERID, receiveDto.getUserId());
        }
        request.getSession().setAttribute(GETRECEIVELOGISTICPAGE, receiveDto);
        model.addAttribute(RESULTLIST, result.getResultList());
        model.addAttribute("dto", receiveDto);
        return "/logistic/receivedLogistic";
    }
    /**
     * 接收
     */
    @RequestMapping(value = "/toReceiveLogisitcPage")
    @ResponseBody
    public Boolean toReceiveLogisitcPage(LogisticDataDto dto,Model model,
        HttpServletRequest request) throws AppException {
        User receiveUser = UserUtil.getCurrentUser();
        if(receiveUser!=null && dto!=null){
            maintainLogisticService.receiveLogistic(dto.getId().toString(), dto.getCardDefId(),
                Integer.parseInt(dto.getReceiveAmount().replaceAll("\\s*", "")),Long.toString(receiveUser.getDealerId()), receiveUser.getId().toString());
            return true;
        }else if(receiveUser==null && dto!=null){
            //MARS 端操作
        	String dealerIdStr = request.getParameter("dealerId");
        	maintainLogisticService.receiveLogistic(dto.getId().toString(), dto.getCardDefId(),
                    Integer.parseInt(dto.getReceiveAmount().replaceAll("\\s*", "")), dealerIdStr, "0");
                return true;
        }
        return false;
    }

    @RequestMapping(value = "/receivedLogistic")
    public String toReceivedLogistic(LogisticQueryDto updateDto, Model model,
            HttpServletRequest request) throws AppException {
        LogisticResultsDto result = new LogisticResultsDto();
        User receiveUser = UserUtil.getCurrentUser();
        if(receiveUser!=null){
            updateDto.setUserId(receiveUser.getId().toString());
            updateDto.setDealerInfo(receiveUser.getUserCode());
        }else{
            String dealerId = request.getParameter("dealerId");
            if(StringUtils.isNotBlank(dealerId)){
                
                updateDto.setUserId(dealerId);
                updateDto.setDealerInfo(dealerId);
            }
        }
        if(request.getSession().getAttribute(TRANSACTIONSTARTDATE) != null){
            updateDto.setTransactionStartDate(request.getSession().getAttribute(TRANSACTIONSTARTDATE).toString());
            }
        if(request.getSession().getAttribute(TRANSACTIONENDDATE) != null){
            updateDto.setTransactionEndDate(request.getSession().getAttribute(TRANSACTIONENDDATE).toString());
            }
        if(request.getSession().getAttribute(ORDERNUM) != null){
            updateDto.setOrderNum(request.getSession().getAttribute(ORDERNUM).toString());
            }
        if(request.getSession().getAttribute(ORDERSTATUS) != null){
            updateDto.setOrderStatus(request.getSession().getAttribute(ORDERSTATUS).toString());
            }
        if(request.getSession().getAttribute(EXPRESSCOM) != null){
            updateDto.setExpressCom(request.getSession().getAttribute(EXPRESSCOM).toString());
            }
        if(request.getSession().getAttribute(EXPRESSNUM) != null){
            updateDto.setExpressNum(request.getSession().getAttribute(EXPRESSNUM).toString());
            }
        if(request.getSession().getAttribute(USERID) != null){
            updateDto.setUserId(request.getSession().getAttribute(USERID).toString());
            }
        if(updateDto != null){
            updateDto.setPaging(true);
            result = maintainLogisticService.queryReceiveLogisticData(updateDto);
        }
        if(updateDto != null) {
             model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, updateDto.getPager());
        }
        model.addAttribute(RESULTLIST, result.getResultList());
        model.addAttribute("dto", updateDto);
        return "/logistic/receivedLogistic";
    }

    /*
     * 导出到Excel
     */
    @RequestMapping(value = "/toQueryLogistic", method = RequestMethod.POST)
	public void toQueryLogistic(LogisticQueryDto dto, HttpServletRequest request, HttpServletResponse response) throws AppException {
        User queryUser = UserUtil.getCurrentUser();
        if(queryUser!=null){
            dto.setUserId(queryUser.getId().toString());
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	    LogisticResultsDto result = new LogisticResultsDto();
        if(dto != null) {
            if(Utils.isNullOrEmpty(dto.getTransactionStartDate())
                ||Utils.isNullOrEmpty(dto.getTransactionEndDate())){
                dto.setTransactionStartDate(df.format(new Date()));
                dto.setTransactionEndDate(df.format(new Date()));
            }
            result = maintainLogisticService.queryAllLogisticData(dto);
//            model.addAttribute("logisticResultsDto", result);
			if (null != result && null != result.getResultList()) {
				List<String> header = new LinkedList<String>();
				header.add("门店编号");
				header.add("门店名称");
				header.add("订单编号");
				header.add("商品名称");
				header.add("实发数量");
				header.add("发货数量");
				header.add("预计到货");
				header.add("物流公司");
				header.add("物流单号");
				header.add("实收数量");
				header.add("收获日期");
				header.add("状态");
				header.add("修改");
				header.add("删除");
				request.setAttribute("logisticExcelHeader", header);
				List<List<String>> listToExport = new LinkedList<List<String>>();
				Iterator<LogisticDataDto> itd = result.getResultList().iterator();
				while(itd.hasNext()) {
					LogisticDataDto item = itd.next();
					List<String> row = new LinkedList<String>();
					row.add(item.getDealerNo());
		            row.add(item.getDealerName());
		            row.add(item.getOrderNo());
		            row.add(item.getCardName());
		            row.add(item.getShipAmount());
		            row.add(item.getShipDate());
		            row.add(item.getEstimatedArriveDate());
		            row.add(item.getExpressCom());
		            row.add(item.getExpressNo());
		            if(Integer.valueOf(null == item.getReceiveAmount() ? "0" : "" == item.getReceiveAmount() ? "0" : item.getReceiveAmount()) <=
		            		Integer.valueOf(null == item.getShipAmount() ? "0" : "" == item.getShipAmount() ? "0" : item.getShipAmount())) {
		            	row.add(item.getReceiveAmount());
		            } else {
		            	row.add("");
		            }
		            row.add(item.getReceiveDate());
		            row.add(item.getStatus());
		            if("在途".equals(item.getStatus())) {
		            	row.add("修改");
		            } else if("已接收".equals(item.getStatus())) {
		            	row.add("");
		            }
		            if("在途".equals(item.getStatus())) {
		            	row.add("删除");
		            } else if("已接收".equals(item.getStatus())) {
		            	row.add("");
		            }
		            listToExport.add(row);
				}
				request.setAttribute("logisticData", listToExport);
				try {
					sc.getContext("/task").getRequestDispatcher("/logisticDataExport/export").forward(request,
							response);
				} catch (ServletException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
        }
    }

	@Override
	public void setServletContext(ServletContext arg0) {
		this.sc = arg0;
	}
}
